﻿using System;
using System.IO;
using System.Windows.Forms;
using QuickTest.Core.Events;
using QuickTest.Core.TestRunner;
using QuickTest.Core.Threading;
using QuickTest.Services.TestRunner;

namespace QuickTest.UI.GuiTester
{
    public partial class TestRunnerForm : Form
    {
        private string solutionPath;
        private readonly string outputDirectory = String.Format(@"{0}QuickTest.AddIn\", Path.GetTempPath());

        private readonly TestRunnerService testRunnerService;
        private readonly IThreadingProvider threadingProvider = new FireAndForgetThreadingProvider();
        private readonly IEventHub eventHub = new EventHub();

        public TestRunnerForm()
        {
            InitializeComponent();

            testRunnerService = new TestRunnerService(threadingProvider, eventHub);
            RegisterTestEvents();
        }

        public void RegisterTestEvents()
        {
            testRunnerControl.Initialize(eventHub);

            eventHub.RunStarted += eventHub_RunStarting;
            eventHub.RunFinished += eventHub_RunFinished;
        }

        private void eventHub_RunStarting(object sender, TestRunStartedEventArgs e)
        {
            runTestsToolStripMenuItem.Enabled = false;
        }

        private void eventHub_RunFinished(object sender, TestRunFinishedEventArgs e)
        {
            runTestsToolStripMenuItem.Enabled = true;
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult result = openFileDialog.ShowDialog(); 
            if (result == DialogResult.OK)
            {
                solutionPath = openFileDialog.FileName;
                runTestsToolStripMenuItem.Enabled = true;
            }
        }

        private void runTestsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            testRunnerService.RunTests(testRunnerControl, solutionPath, outputDirectory);
        }
    }
}
